import copy
from flask_login import UserMixin
from conf.db import get_db


class User(UserMixin):
    attr = None
    cfg = [
        {'label': 'ID', 'field': 'id', 'required': True},
        {'label': '名称', 'field': 'name', 'required': True},
        {'label': '登录账号', 'field': 'account', 'required': True},
    ]

    def __init__(self, _id):
        self.id = _id

    def set_attribute(self, account=None):
        self.attr = get_db().find('users', 'id = {}'.format(self.id))
        if account is not None:
            self.attr = get_db().find('users', 'account = "{}"'.format(account))

    @classmethod
    def edit_cfg(cls):
        cfg = copy.deepcopy(cls.cfg)
        for field in ['id']:
            for idx, itm in enumerate(cfg):
                if itm['field'] == field:
                    del cfg[idx]
                    break
        cfg.append({'label': '密码', 'field': 'passwd', 'required': True})
        for i in cfg:
            i['type'] = 'text'
        return cfg
